package com.shanjupay.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 *  七牛云
 *      文件上传工具类
 *
 *
 *
 *
 */
public class QiniuUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(QiniuUtils.class);

    public static String accessKey = "" ;

    public static String secretKey = "" ;

    public static String bucket = "" ;

    // 提供上传文件的工具方法 accessKey  ,secretKey  ,bucket ,fileName

    /**
     *  文件上传的工具方法
     *
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param bytes
     * @param fileName
     * @return
     */
    public static String upload2Qiniu(String accessKey,String secretKey,String bucket,byte[] bytes ,String fileName) throws RuntimeException{

        //构造一个带指定 Region 对象的配置类
        // 指定存储区域在哪- 指定上传报错
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            // 认证
            Auth auth = Auth.create(accessKey, secretKey);
            // 认证通过后得到token(令牌)
            String upToken = auth.uploadToken(bucket);
            try {
                // 上传文件： 参数： 字节数组， key, token 令牌
                // key： 建议我们自己生成一个不重复的名车
                Response response = uploadManager.put(bytes, fileName, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                //System.err.println(r.toString());
                LOGGER.error("上传文件到七牛：{}",r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
                throw new RuntimeException(r.bodyString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("上传文件到七牛报错：{}",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }



    private static void   testUploadFile() {

        //构造一个带指定 Region 对象的配置类
        // 指定存储区域在哪- 指定上传报错
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "7jlO45VIDCdB-Z1MUn87u6XDDCgFDwX1ZqOH9uh1";
        String secretKey = "rEIOlkGzHt-luPK3An_uub4Q1bHp8WK0K6Hz5ouT";
        String bucket = "hk8s-shanjupay";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString() +".png";
        FileInputStream fileInputStream = null;
        try {
            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            String filePath = "d:\\bgColor.jpg" ;

            fileInputStream = new FileInputStream(new File(filePath));
            // 得到本地文件的字节数组
            byte[] bytes = IOUtils.toByteArray(fileInputStream);
            // 认证
            Auth auth = Auth.create(accessKey, secretKey);
            // 认证通过后得到token(令牌)
            String upToken = auth.uploadToken(bucket);
            try {
                // 上传文件： 参数： 字节数组， key, token 令牌
                // key： 建议我们自己生成一个不重复的名车
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                // System.err.println(r.toString());

                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (
                UnsupportedEncodingException | FileNotFoundException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static  void  testDownload() throws Exception
    {
        String fileName = "5f25b5b3-dc43-4718-af1d-65f251aa527f.png";

        String domainOfBucket = "http://qnsrds4qg.hn-bkt.clouddn.com";

        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");

        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        String accessKey = "7jlO45VIDCdB-Z1MUn87u6XDDCgFDwX1ZqOH9uh1";
        String secretKey = "rEIOlkGzHt-luPK3An_uub4Q1bHp8WK0K6Hz5ouT";
        String bucket = "hk8s-shanjupay";
        Auth auth = Auth.create(accessKey, secretKey);

        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
    }
    public static void main(String[] args) throws Exception {
       // testUploadFile();
        testDownload();
    }























}
